package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.SettableFuture;

import java.util.concurrent.ExecutionException;

/**
 * 手动设置失败异常
 *
 * @author yangyunjiao
 */
public class SettableFutureExceptionDemo {
    public static void main(String[] args) {
        SettableFuture<Integer> future = SettableFuture.create();

        // 模拟业务处理失败
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                // 模拟异常（如数据库连接失败）
                Exception exception = new RuntimeException("数据库连接超时");

                // 设置失败异常
                future.setException(exception);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        // 等待结果（失败时会抛出 ExecutionException）
        try {
            Integer result = future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            // 原始异常通过 e.getCause() 获取
            System.out.println("业务处理失败：" + e.getCause().getMessage());
            // 输出 "业务处理失败：数据库连接超时"
        }
    }
}
